<template>
  <div>
    <van-index-bar :index-list="indexList">
      <!-- template 最终不会解析 只作为容器包裹 -->
      <template v-for="item in city">
        <!-- van-index-anchor 每一个索引项 -->
        <van-index-anchor :index="item.letter" :key="item.letter" />
        <!-- 每一个索引项下的一条 -->
        <van-cell
          v-for="item1 in item.data"
          :title="item1.name"
          :key="item1.cityId"
          @click="chooseCity(item1.cityId, item1.name)"
        />
      </template>
    </van-index-bar>
  </div>
</template>
<script>
import Vue from "vue";
import { IndexBar, IndexAnchor, Cell, Button } from "vant";

Vue.use(IndexBar);
Vue.use(IndexAnchor);
Vue.use(Cell);
Vue.use(Button);
export default {
  data() {
    return {
      citys: [],
    };
  },
  mounted() {
    this.getData();
  },
  computed: {
    indexList() {
      let tmp = [];
      this.citys.forEach((el) => {
        console.log(el);
        let letter = el.pinyin.substr(0, 1).toUpperCase();
        if (!tmp.includes(letter)) {
          tmp.push(letter);
        }
      });
      return tmp.sort();
    },
    city() {
      let arr = [];
      this.indexList.forEach((item) => {
        let obj = {};
        obj.letter = item;
        // item 每一个首字母
        let data = [];
        this.citys.forEach((item1) => {
          let tmp = {};
          // item1 每一个城市的对象数据
          if (item === item1.pinyin.substr(0, 1).toUpperCase()) {
            tmp.cityId = item1.cityId;
            tmp.name = item1.name;
            data.push(tmp);
          }
        });
        obj.data = data;
        // console.log(obj)
        arr.push(obj);
      });
      return arr;
    },
  },
  methods: {
    chooseCity(a, b) {
          localStorage.setItem("token", b);
          localStorage.setItem("ip", a);
           this.$router.push({
            path: "movie",
          });
    },
    getData() {
      this.$http
        .get("/pkq/getCitiesInfo?cors=T")
        .then((res) => {
          console.log(res);
          this.citys = res.data.cities;
        })
        .catch((err) => {});
    },
  },
};
</script>